package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chen.entity.*;
import com.chen.mapper.CartItemMapper;
import com.chen.mapper.ProductFullReductionMapper;
import com.chen.mapper.ProductLadderMapper;
import com.chen.mapper.ProductMapper;
import com.chen.service.CartItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.utils.UserThreadLocal;
import com.chen.vo.CartProduct;
import com.chen.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author cws
 * @since 2024-11-26
 */
@Service
@Slf4j
public class CartItemServiceImpl extends ServiceImpl<CartItemMapper, CartItem> implements CartItemService {


    @Resource
    ProductMapper productMapper;
    @Resource
    ProductLadderMapper productLadderMapper;
    @Resource
    ProductFullReductionMapper productFullReductionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addCart(CartItem cartItem) {
        User user = UserThreadLocal.get();
        cartItem.setUserId(user.getId());
        cartItem.setCreateDate(LocalDateTime.now());
        LambdaQueryWrapper<CartItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CartItem::getUserId, user.getId());
        if (cartItem.getProductSkuId() != null) {
            wrapper.eq(CartItem::getProductSkuId, cartItem.getProductSkuId());
        }
        wrapper.eq(CartItem::getProductId, cartItem.getProductId());
        CartItem cartItemUpdate = baseMapper.selectOne(wrapper);
        if (!Objects.isNull(cartItemUpdate)) {
//            修改数量
            cartItemUpdate.setQuantity(cartItemUpdate.getQuantity() + cartItem.getQuantity());
            baseMapper.updateById(cartItemUpdate);
        } else {
            baseMapper.insert(cartItem);
        }
        return Result.success();
    }

    /**
     * 加一
     *
     * @param id
     * @return
     */
    @Override
    public Result addOne(Long id) {
        int i = baseMapper.quantityAddOnne(id);
        return i == 1 ? Result.success() : Result.fail();
    }

    @Override
    public Result minusOne(Long id) {
        int i = baseMapper.quantityMinusOnne(id);
        return i == 1 ? Result.success() : Result.fail();
    }

    /**
     * 根据用户id查询购物车
     *
     * @return
     */
    @Override
    public Result ByUserOfCartList() {
        User user = UserThreadLocal.get();
        List<CartItem> cartItems = baseMapper.ByUserOfCartList(user.getId());
        return Result.success(cartItems);
    }

    @Override
    public Result deleteCartItemByIds(List<Long> ids) {
        return this.removeByIds(ids) ? Result.success() : Result.fail();
    }

    @Override
    public List<CartProduct> getCartProduct(List<Long> ids) {
        List<CartProduct> cartProductList = baseMapper.getCartProduct(ids);
//        处理价格
        for (CartProduct cartProduct : cartProductList) {
            Product product = productMapper.selectOne(new LambdaQueryWrapper<Product>().eq(Product::getId, cartProduct.getProductId()));
            if (product.getPromotionType() == 1) {
//                查询对应阶梯价格
                Integer quantity = cartProduct.getQuantity();
                List<ProductLadder> productLadders = productLadderMapper.selectList(new LambdaQueryWrapper<ProductLadder>()
                        .eq(ProductLadder::getProductId, product.getId())
                        .orderByDesc(ProductLadder::getCount));
                if (productLadders.size() > 0) {
                    ProductLadder productLadder = null;
                    for (ProductLadder ladder : productLadders) {
                        if (quantity >= ladder.getCount()) {
                            productLadder = ladder;
                        }
                    }
                    if (productLadder != null){
                        //                     拼接名称
                        String promotionName = "满" + productLadder.getCount() + "件打" + productLadder.getDiscount() + "折";
                        cartProduct.setPromotionName(promotionName);
//                    折扣
                        BigDecimal discount = productLadder.getDiscount().divide(BigDecimal.valueOf(10));
//                    折后价格
                        BigDecimal discountPrice = cartProduct.getPrice().multiply(discount)
                                .setScale(2, BigDecimal.ROUND_HALF_UP);
                        cartProduct.setTotalPrice(discountPrice);
//                 原价格减去折后价格=优惠金额
                        cartProduct.setPromotionAmount(cartProduct.getPrice().subtract(discountPrice));
                        log.info("优惠信息：原价：{},折数：{},折后价格：{},优惠金额：{},小计：{}", cartProduct.getPrice(), discount, discountPrice, cartProduct.getPromotionAmount(), cartProduct.getTotalPrice());
                    }else {
                        cartProduct.setPromotionName("无优惠");
                        cartProduct.setPromotionAmount(BigDecimal.ZERO);
                        cartProduct.setTotalPrice(cartProduct.getPrice());
                    }
                }
            }else if (product.getPromotionType() == 2){
                List<ProductFullReduction> productFullReductions = productFullReductionMapper.selectList(new LambdaQueryWrapper<ProductFullReduction>()
                        .eq(ProductFullReduction::getProductId, product.getId())
                        .orderByDesc(ProductFullReduction::getFullPrice));
                if (productFullReductions.size() > 0) {
                    ProductFullReduction productFullReduction = null;
                    for (ProductFullReduction fullReduction : productFullReductions) {
                        if (cartProduct.getPrice().compareTo(fullReduction.getFullPrice()) > 0) {
                            productFullReduction = fullReduction;
                        }
                        if (productFullReduction != null){
                            //   拼接名称
                            String promotionName = "满" + productFullReduction.getFullPrice() + "元减" + productFullReduction.getReducePrice() + "元";
                            cartProduct.setPromotionName(promotionName);
//                            原价格减去优惠价格
                            BigDecimal divide = cartProduct.getPrice().subtract(productFullReduction.getReducePrice());
                            cartProduct.setTotalPrice(divide);
                            cartProduct.setPromotionAmount(cartProduct.getPrice().subtract(divide));
                            log.info("优惠信息：原价：{},满：{},减：{},优惠金额：{},小计：{}", cartProduct.getPrice(), productFullReduction.getFullPrice(), productFullReduction.getReducePrice(), cartProduct.getPromotionAmount(),cartProduct.getTotalPrice());
                        }else {
                            cartProduct.setPromotionName("无优惠");
                            cartProduct.setPromotionAmount(BigDecimal.ZERO);
                            cartProduct.setTotalPrice(cartProduct.getPrice());
                        }
                    }
                }

            }else {
                cartProduct.setPromotionName("无优惠");
                cartProduct.setPromotionAmount(BigDecimal.ZERO);
                cartProduct.setTotalPrice(cartProduct.getPrice());
            }
        }
            return cartProductList;
    }
}
